package com.example.plugin.hook;


import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import com.example.plugin.AMSHookHelper;

import java.lang.reflect.Field;

/**
 * author: zhouyh
 * created on: 2/4/21 4:29 PM
 * description:
 */
public class ActivityThreadHandlerCallback implements Handler.Callback {


    Handler mBase;

    public ActivityThreadHandlerCallback(Handler mBase) {
        this.mBase = mBase;
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        
        switch (msg.what){
            //ActivityThread里面"LAUNCH_ACTIVITY"这个字段的值是100
            //本来使用反射的方式获取最好，这里为了简便直接使用硬编码
            case 100:
                handleLaunchActivity(msg);
                break;
        }

        mBase.handleMessage(msg);

        return true;
    }

    private void handleLaunchActivity(Message msg) {
        //这里简单起见，直接取出TargetActivity
        Object obj = msg.obj;
        //根据源码
        //这个对象是ActivityClientRecord类型
        //我们修改它的intent字段为我们原来保存的即可

        //把替身恢复成真身
        try {
            Field intent = obj.getClass().getDeclaredField("intent");
            intent.setAccessible(true);
            Intent raw = (Intent) intent.get(obj);
            Intent target = raw.getParcelableExtra(AMSHookHelper.EXTRA_TARGET_INTENT);
            raw.setComponent(target.getComponent());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
